package ch1;

class Stud2 {
    public int no;          //存放学号
    public String name;     //存放姓名
    public int score;       //存放分数
    public Stud2 next;      // 链式，我后面的对象

    public Stud2(int no, String name, int score) {
        this.no = no;
        this.name = name;
        this.score = score;
        this.next = null;
    }
}

public class Store2 {
    public static int Findi(Stud2 head, int i) {   //求序号为i的学生分数
        int j = 0;
        Stud2 p = head;                //p指向第一个结点
        while (j < i && p != null) {
            j++;
            p = p.next;
        }
        if (i < 0 || p == null) {       //i错误时抛出异常
            throw new IllegalArgumentException("参数i错误");
        }
        else {                          //i正确时返回分数
            return p.score;
        }
    }

    public static void main(String[] args) {
        // 创建学生单链表
        Stud2 p1 = new Stud2(2018001, "王华", 90);
        Stud2 p2 = new Stud2(2018010, "刘丽", 62);
        Stud2 p3 = new Stud2(2018006, "陈明", 54);
        Stud2 p4 = new Stud2(2018009, "张强", 95);
        Stud2 p5 = new Stud2(2018007, "许兵", 76);
        Stud2 p6 = new Stud2(2018012, "李萍", 88);
        Stud2 p7 = new Stud2(2018005, "李英",82);

        Stud2 head = p1;    //学生单链表开始结点, 建立结点之间的关系
        p1.next = p2;
        p2.next = p3;
        p3.next = p4;
        p4.next = p5;
        p5.next = p6;
        p6.next = p7;
        p7.next = null;

        Stud2 p = head;
        for (; p != null; p = p.next) {
            System.out.println(p.no + " " + p.name + " " + p.score);
        }
        int i = 0;
        System.out.printf("序号为%d的学生分数=%d\n", i, Findi(head, i));
    }
}

